package com.liuceng.dsp.util;

import com.liuceng.dsp.service.AdminService;
import com.liuceng.dsp.pojo.domain.Admin;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * Created by songyu on 2017/02/13.
 */

public class MyRealm extends AuthorizingRealm {

    @Autowired
    AdminService adminService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals){
        SimpleAuthorizationInfo simpleAuthorInfo = new SimpleAuthorizationInfo();
        //添加权限
        simpleAuthorInfo.addStringPermission("admin:list");
        return simpleAuthorInfo;
    }


    /**
     * 验证当前登录的权限
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken)authcToken;
        Admin user = adminService.getAdmin(token.getUsername());
        if(null != user){
            System.out.print(this.getName());
            AuthenticationInfo authcInfo = new SimpleAuthenticationInfo(user.getName(), user.getPassword(), this.getName());
            this.setSession("Admin", user);
            return authcInfo;
        }else{
             return null;
        }
    }

    /***
     * 将登陆信息添加到session中
     * @param key
     * @param value
     */
    private void setSession(Object key, Object value){
        Subject currentUser = SecurityUtils.getSubject();
        if(null != currentUser){
            Session session = currentUser.getSession();
            session.setTimeout(20);
            System.out.println("Session默认超时时间为[" + session.getTimeout() + "]毫秒");
            if(null != session){
                session.setAttribute(key, value);
            }
        }
    }
}